/**
 * @description 本地 jwt 策略文件
 * @author LI
 * @date 2020-11-13 16:34
 */
import { Injectable } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { IStrategyOptions, Strategy } from 'passport-local'
import { AuthService } from './auth.service'
import { ResultFormat } from '../../format/ResultFormat'

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      usernameField: 'loginEmail',
      passwordField: 'password'
    } as IStrategyOptions)
  }

  async validate(loginEmail, password): Promise<any> {
    const user = await this.authService.validateUser({ loginEmail, password })
    if (!user) {
      return new ResultFormat(0, null, false, '授权失败')
    }

    return new ResultFormat(0, user, true, '授权成功')
  }
}
